<script setup>
import { editAPI, getInfoAPI } from "@/apis/form";
import { onMounted, ref } from "vue";

//
const form = ref({
  username: "",
  password: "",
  avata: "",
  file: null,
});

onMounted(async () => {
  const token = localStorage.getItem("token");
  if (token) {
    const res = await getInfoAPI();
    form.value.username = res.data.username;
    form.value.password = res.data.password;
    form.value.avata = "/api" + res.data.avata;
  }
});

const edit = async () => {
  const formData = new FormData();
  if (form.value.file) {
    formData.append("file", form.value.file);
  }
  formData.append("username", form.value.username);
  formData.append("password", form.value.password);
  const res = await editAPI(formData);
};

const imgChange = async (e) => {
  const file = e.target.files[0];
  if (file) {
    form.value.file = file;
    form.value.avata = URL.createObjectURL(file);
  }
};
</script>

<template>
  <form>
    <div>
      <label for="username">用户名：</label>
      <input type="text" v-model="form.username" />
    </div>
    <div>
      <label for="password">密码：</label>
      <input type="text" v-model="form.password" />
    </div>
    <div>
      <label for="avata">头像：</label>
      <img :src="form.avata" alt="" />
      <input type="file" @change="imgChange" />
    </div>
  </form>
  <button @click="edit">修改</button>
</template>

<style lang="scss" scoped>
img {
  width: 100px;
  height: 100px;
  object-fit: fill;
}
</style>
